<template>
  <div class="my-cover">
    <!-- 图片按钮 -->
    <div class="btn_img" @click="openDialog()">
      <img :src="coverImageUrl" />
    </div>
    <!-- 对话框 -->
    <el-dialog
      :append-to-body="true"
      :visible.sync="dialogVisible"
      width="720px">
      <!-- tab组件 -->
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="素材库" name="image">
            <div style="padding-bottom: 20px;">
                <el-radio-group v-model="isCollect" size="mini" @change="hCollect">
                  <el-radio-button :label="false">全部</el-radio-button>
                  <el-radio-button :label="true">收藏</el-radio-button>
                </el-radio-group>
            </div>
            <!-- 素材列表 -->
            <el-row :gutter="10" class="img_list">
                <el-col class="img_item"
                v-for="img in images"
                :key="img.id"
                :span='4'>
                    <el-image
                        style="height: 100px;"
                        :src="img.url"
                        :class="{selected: img.url===selectedImageUrl}"
                        @click="hSelect(img)"
                        fit="cover"></el-image>
                </el-col>
            </el-row>
            <!-- /素材列表 -->
            <!-- 分页组件 -->
            <!-- 只有一页的时候不显示  hide-on-single-page -->
            <el-pagination
                background
                hide-on-single-page
                style="margin-top:10px"
                layout="prev, pager, next"
                @current-change="hCurrentchange"
                :total="total_count"
                >
            </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="上传图片" name="upload">
          <el-upload
            class="avatar-uploader"
            action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
            :headers="headers"
            name="image"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-image v-if="imageUrl" :src="imageUrl" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="hCofirmImage">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import defaultImg from '@/assets/default.png'
export default {
  name: 'MyCover',
  props: ['value'],
  data () {
    return {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      },
      imageUrl: '', // 上传图片时预览地址
      coverImageUrl: this.value || defaultImg, // 图片按钮默认的图片
      selectedImageUrl: null, // 记录当前用户选中的是哪一张图片
      images: [],
      isCollect: false,
      curPage: 1,
      total_count: 0,
      // 控制对话框显示隐藏，false是不显示
      dialogVisible: false,
      // 当前tabs组件激活的选项卡的name属性的值
      activeName: 'image'
    }
  },
  methods: {
    // 确认选中的图片
    hCofirmImage () {
      // 选择素材库
      if (this.activeName === 'image') {
        if (this.selectedImageUrl) {
          // 把选中的按钮显示在图片按钮上
          this.coverImageUrl = this.selectedImageUrl
          // 2. 抛出事件，实现v-model的子传父
          this.$emit('input', this.coverImageUrl)
          // 关闭弹层
          this.dialogVisible = false
        } else {
          this.$message.warning('请选中一张图片')
        }
      } else {
        // 选择上传
        if (this.imageUrl) {
          // 把上传成功的图片显示在图片按钮上
          this.coverImageUrl = this.imageUrl
          // 2. 抛出事件，实现v-model的子传父
          this.$emit('input', this.coverImageUrl)
          // 关闭弹层
          this.dialogVisible = false
        } else {
          this.$message.warning('请上传一张图片')
        }
      }
    },
    openDialog () {
      this.dialogVisible = true
      // 重置工作
      this.activeName = 'image' // 让素材库处理选中状态
      this.imageUrl = null // 清空上传成功之后预览图片地址
      this.selectedImageUrl = '' // 清空上次选择的结果
      this.loadImages()
    },
    // 上传素材
    handleAvatarSuccess (res, file) {
      console.log(res)
      this.imageUrl = res.data.url
      this.$message.success('上传素材成功')
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 实现选中效果
    hSelect (img) {
      console.log(img)
      this.selectedImageUrl = img.url
    },
    // 点击切换全部和收藏功能
    hCollect () {
      // console.log(this.isCollect)
      this.curPage = 1
      this.loadImages()
    },
    // 分页
    hCurrentchange (curPage) {
      this.curPage = curPage
      this.loadImages()
    },
    async loadImages () {
      const result = await this.$http({
        method: 'GET',
        url: '/mp/v1_0/user/images',
        params: {
          collect: this.isCollect,
          page: this.curPage,
          per_page: 10
        }
      })
      console.log(result)
      this.images = result.data.data.results
      this.total_count = result.data.data.total_count
    }
  }
}
</script>

<style scoped lang='less'>
// 图片按钮
.btn_img {
  width: 150px;
  height: 150px;
  border: 1px dashed #ddd;
  img {
    width: 100%;
    height: 100%;
    display: block;
  }
}
.selected::after{
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.3) url(../assets/selected.png) no-repeat center / 50px 50px;
  }
// 素材列表

  .img_item{
    position: relative;
  }
.avatar-uploader {
    text-align: center;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar-uploader /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
</style>
